<template>
  <el-cascader
    v-model="selectedArea"
    :options="options"
    :props="props"
    @change="onChange"
    size="small"
    placeholder="请选择"
    clearable
    :show-all-levels="false"
    filterable
    popper-append-to-body
    :expand-trigger="'hover'"
  >
    <!-- 自定义选项插槽 -->
    <template #default="{ node, data, store }">
      <el-checkbox
        :label="data.areaCode"
        :checked="isChecked(data)"
        @change="handleCheckboxChange(data)"
      >
        {{ data.name }}
      </el-checkbox>
    </template>
  </el-cascader>
</template>

<script>
export default {
  name: 'SingleSelectCascader',
  props: {
    value: {
      type: [String, Number, Array],
      default: ''
    },
    options: {
      type: Array,
      required: true
    },
    props: {
      type: Object,
      default: () => ({
        label: 'name',
        value: 'areaCode',
        children: 'children'
      })
    }
  },
  data() {
    return {
      selectedArea: this.value,  // 双向绑定的选择值
    };
  },
  methods: {
    // 判断当前选项是否是已选中
    isChecked(data) {
      return this.selectedArea === data.areaCode;
    },

    // 处理复选框点击
    handleCheckboxChange(data) {
 
      if (this.selectedArea === data.areaCode) {
        // 如果已经选中该项，取消选择
        this.selectedArea = null;
      } else {
        // 否则选中该项
        this.selectedArea = data.areaCode;
      }
      // 触发 v-model 双向绑定
      this.$emit('input', this.selectedArea);
    },

    // 选择变化处理
    onChange(value) {
      // 如果选择变化，更新选择的值
      this.selectedArea = value;
      this.$emit('input', this.selectedArea);
    },

    // 禁用父节点
    isDisabled(data) {
      // 只有叶子节点才可以选择
      return !data.children || data.children.length === 0;
    }
  }
};
</script>

<style scoped>
.el-checkbox {
  display: flex;
  align-items: center;
}
</style>
